package com.anjiplus.template.gaea.business.config.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;

/*
 * @author Administrator
 * @title: MybatisPlusConfig
 * @projectName springboot-demo
 * @description:
 * @date 2019/9/18 0018下午 17:09
 */

@Configuration
@Slf4j
@Order(value = 1)
public class MybatisPlusConfig {

    @Autowired
    private DataSource dataSource;


    @Bean("paginationInterceptor1")
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 指定数据库方言为 MYSQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE));
        //乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }


    @Bean("mybatissqlSessionFactory")
    public SqlSessionFactory mybatissqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        //开启log日志打印
//        configuration.setLogImpl(StdOutImpl.class);
        sqlSessionFactory.setVfs(SpringBootVFS.class);
        // 设置 Mybatis-Plus 全局配置
        sqlSessionFactory.setGlobalConfig(globalConfig());

        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(
                paginationInterceptor()
        );
        return sqlSessionFactory.getObject();
    }

    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        // 配置全局的 column-format
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setColumnFormat("\"%s\"");  // 设置列名的格式
        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }

}
